import { Router } from 'vue-router'
import {$local} from "@/utils/local"
import {$pathTo} from "@/utils/pathTo"
import {appToken,baseStoreState} from '@/utils/dict'

export function createRouterGuards (router: Router) {
  router.beforeEach((to, _from, next) => {
    const token = $local(appToken);
    const baseStore = $local(baseStoreState);
    document.title = to?.meta?.title as string || document.title;
    if(!baseStore.netState && to?.meta && (to.meta.permissions as Array<any> || []).indexOf('offLine') == -1){
      $pathTo('@'+process.env.VUE_APP_HOME)
      return;
    }
    if(!token && to?.meta && to.meta.public !== true){
      $pathTo(process.env.VUE_APP_LOGIN as string)
      return;
    }
    if(token && to?.path == '/login'){
      $pathTo('@'+process.env.VUE_APP_HOME)
      return;
    }
    next()
  })
}